package com.down;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhanghui
 * @date 2021/12/3 11:41
 */
public class DownTsListWithStart {
    // 最后一个ts文件的下载连接
    private static String url = "";
    // 文件保存的文件夹
    private static String saveDir = "myVideo";
    // 文件序号之前的部分
    private static String prePartition = null;
    // 文件序号之后的部分
    private static String sufPartition = null;

    public static void downLoadFromUrl(int startIndex, String lastUrlStr, String savePath) throws IOException {
        if (lastUrlStr == null || (!lastUrlStr.startsWith("http") && !lastUrlStr.startsWith("https"))) {
            System.out.println("请输入正确的链接");
            return;
        }

        int fileCount = getFileCountByUrl(lastUrlStr);
        String urlStr;
        long fileStartDownTime = System.currentTimeMillis();

        // 生成目录
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            boolean mkdirStatus = saveDir.mkdir();
            if (!mkdirStatus) {
                System.out.println("文件创建失败");
                return;
            } else {
                System.out.println(saveDir.getPath() + " 创建成功");
            }
        }

        System.out.println("============开始下载===========");
        for (int i = startIndex; i < fileCount; i++) {
            urlStr = getFileNameByIndex(lastUrlStr, i);

            // 建立url连接并获取输入流
//            URL url = new URL(URLEncoder.encode(urlStr, "UTF-8"));
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = connection.getInputStream();

            // 获取文件输出流用于保持文件
            String fileName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
            File saveFile = new File(saveDir + File.separator + fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(saveFile);

            long currentStartDownTime = System.currentTimeMillis();
            // 读取数据并写入文件
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
                fileOutputStream.flush();
            }
            long currentEndDownTime = System.currentTimeMillis();
            System.out.println(fileName + "下载完成, 耗时" + (currentEndDownTime - currentStartDownTime) * 1.0 / 1000 + "秒");
            inputStream.close();
            fileOutputStream.close();
        }
        long fileEndDownTime = System.currentTimeMillis();
        System.out.println("文件全部下载完成, 耗时" + (fileEndDownTime - fileStartDownTime) * 1.0 / 1000 + "秒");
    }

    public static void main(String[] args) throws IOException {
        if (args.length == 2) {
            url = args[0];
            saveDir = args[1];
        }

        if (args.length != 0 && args.length != 2) {
            System.out.println("参数输入错误");
            return;
        }

        // 安装路径在用户目录下
        String savePath = System.getProperty("user.home") + File.separator + saveDir;
        int startIndex = 329;
        DownTsListWithStart.downLoadFromUrl(startIndex, url, savePath);
    }

    /**
     * 从url中获取文件数量
     *
     * @param url
     * @return
     */
    private static int getFileCountByUrl(String url) {
        return Integer.parseInt(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'))) + 1;
    }

    /**
     * 获取文件名称
     *
     * @param originalName
     * @param index
     * @return
     */
    private static String getFileNameByIndex(String originalName, int index) {
        if (prePartition == null) {
            prePartition = originalName.substring(0, originalName.lastIndexOf('/'));
        }
        if (sufPartition == null) {
            sufPartition = originalName.substring(originalName.lastIndexOf('.'));
        }
        return prePartition + '/' + index + sufPartition;
    }

}
